<template>
  <div>
    <div>
      <el-input
        size="medium"
        class="selectInput"
        placeholder="输入关键字查询"
        v-model="selectKey"
        suffix-icon="el-icon-circle-plus-outline">
      </el-input>
      <el-button
        size="medium" type="success" plain @click="doSearch">查询
      </el-button>
      <el-tooltip class="item" effect="dark" content="查看更多商品，去租赁！！！" placement="right">
        <el-button @click="toMain" size="medium" type="info" icon="el-icon-more-outline" plain></el-button>
      </el-tooltip>
    </div>
    <div>
      <el-table
        border
        height="486"
        ref="tableData"
        :data="tableData"
        style="width: 100%;"
        @expand-change="handle_list"
        :default-sort = "{prop: 'createTime', order: 'descending'}">
        <el-table-column prop="children" type="expand" label="查看商品" width="80px">
          <template slot-scope="scope">
            <el-table
              stripe
              border
              :data="scope.row.children"
              tooltip-effect="light"
              style="width: 100%"
              :cell-style="{padding: '0'}">
              <el-table-column
                prop="goodId"
                label="商品编号"
                width="80">
              </el-table-column>
              <el-table-column
                property="goodName"
                label="商品名称"
                :show-overflow-tooltip="true"
                width="180">
              </el-table-column>
              <el-table-column
                property="category"
                label="商品类型"
                width="100">
              </el-table-column>
              <el-table-column
                property="imgurl"
                label="商品图"
                width="70">
                <template #default="scope">
                  <el-image class="table-td-thumb" :src="scope.row.imgurl" :preview-src-list="[scope.row.imgurl]">
                  </el-image>
                </template>
              </el-table-column>
              <el-table-column
                property="rentPriceHour"
                label="价格/小时"
                width="90">
              </el-table-column>
              <el-table-column
                property="rentPriceDay"
                label="价格/天"
                width="80">
              </el-table-column>
              <el-table-column
                property="brand"
                label="商品品牌"
                width="120">
              </el-table-column>
              <el-table-column
                property="goodNewold"
                label="新旧程度"
                width="120">
              </el-table-column>
              <el-table-column
                property="description"
                label="商品描述"
                width="220"
                :show-overflow-tooltip="true">
              </el-table-column>
              <el-table-column
                property="description"
                label="使用需知"
                width="230"
                :show-overflow-tooltip="true">
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column
        prop="rentId"
        label="租赁编号"
        sortable
        width="120">
      </el-table-column>
        <el-table-column
          prop="goodId"
          label="商品编号"
          sortable
          width="110">
        </el-table-column>
        <el-table-column
          prop="number"
          label="数量"
          width="50">
        </el-table-column>
        <el-table-column
          prop="singlePrice"
          label="价格/小时"
          width="90">
          <template slot-scope="scope">
            {{scope.row.singlePrice==null?'-':scope.row.singlePrice}}
          </template>
        </el-table-column>
        <el-table-column
          prop="dayPrice"
          label="价格/天"
          width="80">
          <template slot-scope="scope">
              {{scope.row.dayPrice==null?'-':scope.row.dayPrice}}
          </template>
        </el-table-column>
        <el-table-column
          prop="yarent"
          label="押金"
          width="80">
        </el-table-column>
        <el-table-column
          prop="tolRentPrice"
          label="总价"
          width="100">
        </el-table-column>
        <el-table-column
          prop="paystate"
          label="支付状态"
          width="80">
          <template slot-scope="scope">
            <el-tag size="small" :type="scope.row.paystate=='0'?'danger':'success'">
            {{scope.row.paystate=='0'?'待付款':'已支付'}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="starttime"
          label="租赁开始时间"
          sortable
          width="180">
        </el-table-column>
          <el-table-column
            prop="endtime"
            label="租赁结束时间"
            sortable
            width="180">
        </el-table-column>
        <el-table-column
          prop="rentTime"
          label="加购时间"
          width="180">
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template slot-scope="scope">
            <!--<el-button-->
              <!--type="primary" size="mini" icon="el-icon-edit" plain-->
              <!--@click="showEditView(scope.$index, scope.row)">-->
            <!--</el-button>-->
            <el-button
              type="danger" size="mini" icon="el-icon-delete" plain
              @click="handleDelete(scope.$index, scope.row)">
            </el-button>
            <el-button
              type="primary" size="mini" @click="showPayView(scope.$index, scope.row)">支付
              <i class="el-icon-coin el-icon--right"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--弹框-->
      <el-dialog title="选择地址" :visible.sync="dialogVisible"
                 style="width: 1800px;margin: auto">
        <div class="user-container">
          <el-card class="user-card" v-for="(address,index) in addList" :key="index" shadow="never">
            <div>
              <div cLass="userinfo-container">
                <div>地址编号: {{address.addressId}}</div>
                <div>收货人: {{address.userName}}</div>
                <div>手机号: {{address.contactPhone}}</div>
                <div>地址: {{address.takeAddres}}</div>
                <div>默认:
                  <el-switch
                    v-model="address.adrsDefault"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    active-text="选用"
                    @change="enabledChange(address)">
                  </el-switch>
                </div>
              </div>
            </div>
          </el-card>
          <el-card class="user-card" shadow="never">
            <div>
              <div>
                <el-button style="font-size: 45px;color: #cccccc;margin-left: 80px;margin-top: 20px"
                           class='el-icon-circle-plus'
                           type="text"
                           @click="addAddress"></el-button>
              </div>
            </div>
          </el-card>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="PayRents">确 定</el-button>
        </span>
      </el-dialog>
      <!--弹框-->
      <el-dialog title="添加地址" :visible.sync="dialogVisibleAddress" :center="true" width="500px">
        <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
          <el-form-item label="收货人姓名" prop="userName">
            <el-input v-model="formData.userName" placeholder="请输入收货人姓名" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
          <el-form-item label="收货人手机" prop="contactPhone">
            <el-input v-model="formData.contactPhone" placeholder="请输入收货人手机" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
          <el-form-item label="默认地址" prop="adrsDefault" required disabled>
            <el-switch v-model="formData.adrsDefault" active-text="默认" active-color="#26D05C"
                       inactive-color="#EF4F4F"></el-switch>
          </el-form-item>
          <el-form-item label="收货地址" prop="takeAddres">
            <el-input v-model="formData.takeAddres" type="textarea" placeholder="请输入收货地址"
                      :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="dialogVisibleAddress=false">取消</el-button>
          <el-button type="primary" @click="handelConfirm">确定</el-button>
        </div>
      </el-dialog>
      <!--弹框-->
      <el-dialog title="支付" :visible.sync="dialogVisiblePay"
                 style="width: 800px;margin: auto">
        <div>
          <div slot="content">
            <div class="box-inner order-info">
              <p class="payment-detail">扫一扫付款（元）</p>
              <p class="payment-money">{{total}}元</p>
              <div class="num">
                <el-button type="text" @click="finishPay">确认支付状态</el-button>
              </div>
              <div class="img-box">
                <img id="qr" class="pic"  src="../../assets/img/pay.jpg" alt="加载失败" width="168px" height="168px"/>
              </div>
            </div>

          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  export default {

    name: 'RentManage',
    data() {
      return {
        user:JSON.parse(window.sessionStorage.getItem('user')),
        tableData: [],
        formData: {
          adrsUserId:undefined,
          userName: undefined,
          contactPhone: undefined,
          adrsDefault: false,
          takeAddres: undefined,
        },
        total:undefined,
        updateAdrs:{},
        addList: [],
        yatolPrice:undefined,
        selectKey:'',
        dialogVisiblePay:false,
        dialogVisibleAddress:false,
        dialogVisible: false,
        rent:{
          id:undefined,
          paystate:1,
          orderAddress:undefined,
        },
        tolRentPrice:undefined,
        good:{},
        time:'0',
        rentTime:[],
        number:undefined,
        hourCount:'',
        dayCount:'',
        updateRent:{
          yarent:undefined,
          rentId:undefined,
          number:undefined,
          singlePrice:undefined,
          dayPrice:undefined,
          tolRentPrice:undefined,
          orderAddress:'',
          starttime:'',
          endtime:'',
          rentTime:'',
        },
        oneAddress:{},
        rules: {
          userName: [{
            required: true,
            message: '请输入收货人姓名',
            trigger: 'blur'
          }],
          contactPhone: [{
            required: true,
            message: '请输入收货人手机',
            trigger: 'blur'
          }],
          takeAddres: [{
            required: true,
            message: '请输入收货地址',
            trigger: 'blur'
          }],
        },
      }
    },
    mounted () {
      this.initTable();
    },
    methods: {
      // 确认支付
      finishPay(){
        this.$confirm('支付成功?', '支付提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 修改租赁状态
          this.putRequest('/rent/data/updateRent',this.rent).then(resp=>{
            this.$notify.success({ title: '成功', message: '订单已支付' });
            this.initTable()
            this.dialogVisiblePay=false
          })
        }).catch(() => {
          this.$notify.info({ title: '消息', message: '已取消' });
          this.dialogVisiblePay=false
        });
      },
      PayRents(){
        this.dialogVisible=false
        this.dialogVisiblePay=true
        // 查询默认地址
        this.getRequest('/rent/address/?userId='+this.user.userId+'&adrsDefault='+true).then(resp=>{
          if (resp){
            this.oneAddress=resp
            console.log("查到了"+this.oneAddress)
            this.rent.orderAddress=this.oneAddress.addressId
          }
        })
      },
      addAddress(){
        this.formData.adrsUserId=this.user.userId
        this.dialogVisibleAddress=true
        this.resetView()
      },
      resetView () {
        this.formData.userName=''
        this.formData.contactPhone=''
        this.formData.takeAddres=''
        this.formData.adrsDefault=false
      },
      // 添加地址
      handelConfirm() {
        // 添加事件
        this.$refs['elForm'].validate(valid => {
          if (!valid) return
          this.postRequest('/rent/address',this.formData).then(resp => {
            if (resp) {
              this.$notify.success({ title: '成功', message: resp.message });
              this.dialogVisibleAddress=false;
              this.initMyAddress()
            }
          })
        })
      },
      //修改地址状态
      enabledChange(data){
        this.updateAdrsHander()
        // 修改地址状态改变
        this.putRequest('/rent/address',data).then(resp=>{
          if (resp){
            console.log("我是默认地址3")
          }
        })
        console.log(data.adrsDefault)
        if(data.adrsDefault){
          this.rent.rentId = this.$route.params.rentName;
          this.rent.orderAddress=data.addressId
          // 修改配送地址状态
          this.putRequest('/rent/data/updateRent',this.rent).then(resp=>{
            if (resp){
              this.$notify.success({ title: '成功'});
              this.initMyAddress();
            }
          })
        }
      },
      updateAdrsHander(){
        // 获取用户的默认地址
        this.getRequest('/rent/address/?userId='+this.user.userId+'&adrsDefault='+true).then(resp=>{
          if (resp){
            this.updateAdrs=resp
            console.log("我是默认地址1",resp)
            this.updateAdrsHander1()
          }
        })
      },
      updateAdrsHander1(){
        // 修改默认地址状态
        if(this.updateAdrs){
          this.updateAdrs.adrsDefault=false
          console.log("我是默认地址2"+this.updateAdrs)
          this.putRequest('/rent/address',this.updateAdrs).then(resp=>{
            if (resp){
            }
          })
        }
      },

      //查询全部地址
      initMyAddress () {
        this.getRequest('/rent/address/'+this.user.userId).then(resp => {
          if (resp) {
            console.log('我呢'+resp);
            this.addList=resp;
          }
        })
      },
      toMain(){
        this.$router.push('/main');
      },
      // 确定修改事件
      updateRents(){
        if (this.rentTime){
          if (this.updateRent.orderAddress){
            var aData = new Date();
            this.updateRent.rentTime=this.transformTimestamp(aData);
            console.log(this.updateRent)
            this.putRequest('/rent/data/updateRent',this.updateRent).then(resp=>{
              if (resp){
                this.$notify.success({ title: '成功', message: '修改成功' });
                this.dialogVisible = false
                this.initTable();
              }
            })

          } else {
            this.$notify.warning({ title: '警告', message: '请输入配送地址' });
          }
        }else {
          this.$notify.warning({ title: '警告', message: '请输入租赁时间段' });
        }
      },
      // 删除
      handleDelete(index,data){
        this.$confirm('此操作将移除租赁商品, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteRequest('/rent/data/delete/'+data.rentId).then(resp=>{
            this.initTable();
          })
          this.$notify.success({ title: '成功', message: '删除成功' });
        }).catch(() => {
          this.$notify.info({ title: '消息', message: '已取消删除' });
        });
      },
      // 点击支付按钮事件
      showPayView(index,data){
        this.dialogVisible=true;
        this.initMyAddress()
        this.total=data.tolRentPrice
        this.rent.rentId=data.rentId
      },
      // 级联查询
      initTable(){
        let userId = parseInt(this.user.userId);
        let url = '/rent/data/list/?userId='+userId+'&&paystate='+'0'+'&&rentState='+''+'&&selectKey='+'';
        this.postRequest(url).then(resp => {
          if (resp) {
            //给每行数据强制追加一个数据项children
            resp.map(item => {
              item.children = [];
            });
            this.tableData = resp;
            console.log(this.tableData);
          }
        });
      },
      handle_list(row,expandedRows) {
        console.log(row);
        console.log(expandedRows);
        if (expandedRows.length > 0) {
          this.postRequest('/rent/data/good/' + row.goodId).then(resp => {
            if (resp) {
              console.log(resp)
              this.tableData.forEach((temp, index) => {
                // 找到当前点击的行，把动态获取到的数据赋值进去
                if (temp.goodId === row.goodId) {
                  if (this.tableData[index].children.length===0) {
                    this.tableData[index].children.push(resp);
                  }
                }

              });
            }
          })
        }else {
          this.tableData.children = [];
        }
      },
      doSearch(){
        if (this.selectKey) {
          this.tableData='';
          let userId = parseInt(this.user.userId);
          let url = '/rent/data/list/?userId='+userId+'&&paystate='+'0'+'&&rentState='+''+'&&selectKey='+this.selectKey;
          this.postRequest(url).then(resp => {
            if (resp) {
              //给每行数据强制追加一个数据项children
              resp.map(item => {
                item.children = [];
              });
              this.tableData = resp;
              console.log(this.tableData);
            }
          });
          this.selectKey='';
        }else{
          this.initTable();
        }
      },

    }
  }
</script>

<style lang="scss" scoped rel="stylesheet/scss">
  .user-container{
    width: 100%;
  }
  .user-card{
    background-color: #ffffff;
    width: 30%;
    height: 150px;
    margin-right: 4px;
    margin-left: 4px;
    margin-top: 10px;
  }
  .minPrice {
    display: block;
    color: #484c49;
    font-weight: 700;
    font-size: 12px;
    line-height: 16px;
    text-align: right;
    i {
      padding-left: 2px;
      font-size: 14px;
    }
  }
  .selectInput{
    width: 220px;
    margin: 10px 10px 10px 15px;
  }
  .price {
    display: block;
    color: #d44d44;
    font-weight: 700;
    font-size: 16px;
    line-height: 20px;
    text-align: right;
    i {
      padding-left: 2px;
      font-size: 24px;
    }
  }
  .item {
    margin: 10px;
  }
  .order-info {
    padding: 60px 0 5px;
    color: #333;
    background: #fff !important;
    h3 {
      padding-bottom: 14px;
      line-height: 36px;
      text-align: center;
      font-size: 36px;
      color: #212121;
    }
    .payment-detail {
      text-align: center;
      line-height: 24px;
      font-size: 14px;
      color: #999;
    }
  }
  .payment-money {
    text-align: center;
    font-size: 30px;
    color: #d44d44;
    font-weight: 700;
  }

  .box-inner {
    line-height: 30px;
    background: #f9f9f9;
    border-top: 1px solid #e5e5e5;
    box-sizing: border-box;
    > div {
      display: flex;
      flex-direction: column;
      justify-content: flex-end;
      align-items: center;
      padding: 0 20px;
    }
    em {
      margin-left: 5px;
      font-size: 24px;
      color: #d44d44;
      font-weight: 700;
      margin-right: 20px;
      span {
        margin-right: 4px;
        font-size: 16px;
      }
    }
  }
</style>
